package com.ruoyi.web.core.config;

import com.ruoyi.common.utils.SseEmitterUtils;
import lombok.extern.slf4j.Slf4j;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Map;


/**
 * @Description SSE心跳
 * @Author liuhl
 * @Date 2024/10/18
 **/
@Component
@Slf4j
public class SseHeartBeatTask {

    //@Scheduled(cron = "10/30 * * * * ?")
    public void run(){

        log.info("开始SSE心跳探测");
        LocalDateTime start = LocalDateTime.now();
        Map<String, SseEmitter> sseEmitterMap = SseEmitterUtils.getSseEmitterMap();
        String message = "HEART_BEAT";
        sseEmitterMap.forEach((k, v) -> {
           try {
               v.send(message);
               log.info("key:{} 发送{}成功", k , message);
           }catch (Exception e){
               log.info("key:{} 发送{}出现异常!!!, e:{}", k , message , e.getMessage());
               SseEmitterUtils.remove(k);
           }
        });
        LocalDateTime end = LocalDateTime.now();
        long millis = Duration.between(start, end).toMillis();
        log.info("结束SSE心跳探测，共{}个key，耗时:{}毫秒", sseEmitterMap.size(), millis);

    }

}
